import React from "react";
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import { renderRoutes } from "react-router-config";
import routes from "../share/routes";

import serialize from 'serialize-javascript';
import Home from '../share/pages/Home';

import { RootStoreProvider } from "../share/store"
import { rootStore } from "../share/store"

export default (cxt) => {
  console.log("cxt.request.path:",cxt.request.path)

  // 1、renderToString()的参数是组件或者DOM字符串；
  // 2、如果渲染量特别大，可以使用renderToNodeStream采用流式渲染
  const content = renderToString(
    <RootStoreProvider>
      <StaticRouter location={cxt.request.path}>{renderRoutes(routes)}</StaticRouter>
    </RootStoreProvider>)

  // 1、将服务端初始状态传递给客户端
  // 2、serialize 转义恶意代码，防止XSS攻击
  const initalState = serialize(rootStore);

  
  return `
    <html>
      <head>
        <title>React SSR</title>
      </head>
      <body>
        <div id="root">${content}</div>
        <script>window.INITIAL_STATE = ${initalState} </script>
        <script src="bundle.js"></script>
      </body>
    </html>
  `;
};
